package com.freez.spark.core.demo;

import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.api.java.function.Function2;
import org.apache.spark.api.java.function.PairFunction;
import org.apache.spark.api.java.function.VoidFunction;
import scala.Tuple2;

import java.util.Arrays;

/**
 * FREEDOM  2021 人生苦短，不妨一试
 * FileName: SumDemo.java
 * Author: zcs
 * Date: 2021年-12月-07日 周二 18:28
 * Description: 一到十累加
 */
public class SumDemo {
    private static final long serialVersionUID = 1L;

    public static void sumDemo() {
        SparkConf conf = new SparkConf();
        conf.setAppName("TestSum").setMaster("spark://slaveNode2:7077")/*.set("spark.submit.deployMode", "cluster")*/;

        JavaSparkContext jsc = new JavaSparkContext(conf);
        JavaRDD<Integer> aRDD = jsc.parallelize(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
        JavaPairRDD<String, Integer> bRDD = aRDD.mapToPair(new PairFunction<Integer, String, Integer>() {
            public Tuple2<String, Integer> call(Integer integer) throws Exception {
                return new Tuple2<String, Integer>("sum", integer);
            }
        });
        Integer sum = aRDD.reduce(new Function2<Integer, Integer, Integer>() {
            public Integer call(Integer v1, Integer v2) throws Exception {
                return v1 + v2;
            }
        });
        System.out.println("1到10的累加：" + sum);
        bRDD.reduceByKey(new Function2<Integer, Integer, Integer>() {
            public Integer call(Integer v1, Integer v2) throws Exception {
                final long serialVersionUID = 1L;
                Integer sum = v1 + v2;
                return sum;
            }
        }).foreach(new VoidFunction<Tuple2<String, Integer>>() {
            public void call(Tuple2<String, Integer> s) throws Exception {
                System.out.println("foreach里面》》》1到10的累加：" + s._1 + " = " + s._2);
            }
        });
        jsc.close();
    }

    public static void main(String[] args) {
//        SimpleDateFormat sft = new SimpleDateFormat("yyyy-mm-dd");
//        Calendar calendar = Calendar.getInstance();
//        String str = "2020-05-02";
//        try {
//            Date date = sft.parse(str);
//
//            System.out.println(date);
//
//            calendar.setTime(date);
//            calendar.add(Calendar.DATE,1);
//            Date time = calendar.getTime();
//
//            System.out.println(time);
//
//            String format = sft.format(time);
//
//            System.out.println(format);
//        } catch (ParseException e) {
//            e.printStackTrace();
//        }

        sumDemo();
    }
}